import {
  add,
  pageHistory
} from '../../api/ai'
import log from '../../utils/log'
import env from '../../config/env'

let ws

Page({

  data: {
    sessionId: '',
    avatarAuto: '/image/logo.png', // 系统头像
    avatarUser: wx.getStorageSync('user').avatar,
    isAnimation: true, // 是否开启动画
    viewHeight: 0, // 设置srcoll-view的高度
    canSend: false, // 是否可发送
    chatDataArray: [], // 对话内容
    useMsg: '', // 用户输入框内的信息
    toView: 'toFooter', // 定位到底部，用于处理消息容器滑动到最底部
    serviceMsg: '随便问，答不出来我是你爹 ！',
    waitServer: false,
    pageNum: 1,
    pageSize: 100000,
    reachTop: false
  },

  // 监听 滑动事件
  scroll(e) {
    if (!this.data.reachTop) {
      const param = {
        pageNum: this.data.pageNum + 1,
        pageSize: this.data.pageSize,
        sessionId: this.data.sessionId
      }

      pageHistory(param).then(res => {
        // const data = res.records.reverse()
        const chatDataArray = res.records.reverse().concat(this.data.chatDataArray)
        this.setData({
          chatDataArray: chatDataArray,
          pageNum: param.pageNum,
          reachTop: chatDataArray.length >= res.total
        })

      })
    }
  },

  // 处理 滑动到底部 动效
  tapMove() {
    this.setData({
      toView: 'toFooter'
    });
  },

  // 监听 底部输入框
  bindInputValue: function (e) {
    const useMsg = e.detail.value;
    if (useMsg.length !== 0) {
      this.setData({
        useMsg,
        canSend: true
      });
    } else {
      this.setData({
        canSend: false
      });
    }
  },

  // 发送聊天信息 
  formSubmit: function (e) {

    let useMsg = this.data.useMsg
    this.setData({
      useMsg: '',
      chatDataArray: this.data.chatDataArray.concat([{
        content: useMsg,
        type: 2
      }, {
        content: '正在回复...',
        type: 1
      }]),
      waitServer: true
    })

    if (!this.data.sessionId) {
      add(useMsg).then(res => {
        this.setData({
          sessionId: res,
          reachTop: true
        })
        this.initWs(useMsg)
      })
      return false
    }

    ws.send({
      data: useMsg
    })
    this.tapMove()
  },

  initWs(msg) {
    const that = this
    ws = wx.connectSocket({
      url: `${env.WS_URL}/ai/ws/chat/${that.data.sessionId}`,
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      }
    })

    ws.onOpen(() => {
      if (msg) {
        ws.send({
          data: msg
        })
      }
    })

    ws.onMessage(message => {
      that.data.chatDataArray[that.data.chatDataArray.length - 1].content = message.data
      that.setData({
        chatDataArray: that.data.chatDataArray,
        waitServer: false
      })
      setTimeout(() => {
        that.tapMove()
      }, 200);
    })

    // ws.onClose(msg => {
    //   log.error(msg.reason)
    //   wx.showToast({
    //     title: '服务器GG，退出后重试',
    //     icon: 'success'
    //   })
    //   wx.navigateBack()
    // })

    ws.onError(msg => {
      log.error(msg.errMsg)
      wx.showToast({
        title: msg,
        icon: 'error'
      })
      wx.navigateBack()
    })
    ws.onClose(data => {
      console.log(data)
    })
  },

  // 处理 设备可显示高度
  getBtnHeight: function () {
    const that = this,
      query = wx.createSelectorQuery();
    query.select('#footerBtnGroup').boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(function (res) {
      const _h = res[0].height * 2 - 15;
      let windowHeight = wx.getSystemInfoSync().windowHeight;
      let windowWidth = wx.getSystemInfoSync().windowWidth;
      const viewHeight = parseInt(750 * windowHeight / windowWidth - _h);
      that.setData({
        viewHeight
      });
      that.tapMove();
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.getBtnHeight(); // 处理 设备可显示高度

    this.setData({
      sessionId: options.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    this.animation = wx.createAnimation(); // 创建动画。
    if (this.data.sessionId) {
      const that = this
      const fnc = this.initWs
      const param = {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
        sessionId: this.data.sessionId
      }

      pageHistory(param).then(res => {
        // const data = res.records.reverse()
        // const chatDataArray = res.records.reverse()
        this.setData({
          chatDataArray: res.records.reverse(),
          reachTop: res.records.length >= res.total
        })
        fnc()

        // 反转有时间，延迟点
        setTimeout(() => {
          that.tapMove()
        }, 200);
      })
    }

  },
  onUnload() {
    wx.closeSocket()
  }
})